<?php
namespace app\admin\controller;

use app\common\model\SystemMenu;
use think\facade\Request;

class Menu
{
	public function index()
	{
		$m = SystemMenu::where('status', 1)->with('meta')->order('id asc')->select();
		// $m = $m->toArray();
		// $mm = $this->array_tree($m, 0);
		$mm = SystemMenu::treeList($m->toArray());
		$menu['menu'] = $mm;
		return json(['code'=>200, 'data' => $menu, 'message' => "1111111"]);
	}

	public function lists()
	{
		$m = SystemMenu::where('status', 1)->with('meta')->order('id asc')->select();
		// $m = $m->toArray();
		// $mm = $this->array_tree($m, 0);
		$mm = SystemMenu::treeList($m->toArray());
		// $menu['menu'] = $mm;
		return json(['code'=>200, 'data' => $mm, 'message' => "1111111"]);
	}

	public static $tree = [];

	public function array_tree ($data, $pid) {
		foreach ($data as $k => $v) {
			if ($v['parent_id'] == $pid) {
				$child = $this->getChildMenu($data, $v['id']);
				if (!empty($child)) {
					$v['children'] = $child;
				}
				self::$tree[] = $v;
			}
		}
		return self::$tree;
	}


	public function getChildMenu ($data, $parent_id) {
		$r = [];
		foreach ($data as $v) {
			if ($v['parent_id'] == $parent_id) {
				$r[] = $v;
			}
		}
		return $r;
	}



	// foreach ($data as $k => $v) {
		// 	// 顶级分类
		// 	if ($v['parent_id'] == $pid) {
		// 		// unset($data[$k]);
		// 		// dump($data);
		// 		// dump($v);
		// 		dump('开始遍历 子 pid: ' . $v['id']);
		// 		$child = self::tree($data, $v['id']);
		// 		dump($child);
		// 		dump("------------------------");
		// 		// if (!empty($child)) {
		// 		// 	$v['children'] = $child;
		// 		// }
		// 		// self::$treeMenu[] = $v;
		// 	}
			
		// }

	/*


  "code": 200,
  "data": {
    "menu": [
	*/

	public function add ()
	{
		$params = request()->only(['parentId', 'name', 'path', 'component']);
		// dump($params);
		$menu = new SystemMenu;
		$menu->save($params);
		// dump(/$menu);
		return json(['code' => 200, 'message' => "success add", 'data' => $menu->id]);
	}

	/* 更新菜单方法 */
	public function edit ()
	{
		$params = Request::only(['id', 'name', 'redirect', 'active', 'path', 'component', 'status']);

		$data = SystemMenu::update($params);

		return json(['code' => 200, 'message' => "menu update", 'data' => $data]);
	}


}